package nl.hva.three2learn.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.hva.three2learn.authentication.UserAuthentication;
import nl.hva.three2learn.model.User;

import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public final class IsLoggedInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		SecurityContext context = SecurityContextHolder.getContext();
		
		if (context.getAuthentication() != null) {
			UserAuthentication authentication = (UserAuthentication) context.getAuthentication();
			
			request.setAttribute("user", authentication.getDetails());
			request.setAttribute("isLoggedIn", true);
		} else {
			request.setAttribute("isLoggedIn", false);	
		}
		
		return super.preHandle(request, response, handler);
	}

}
